﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using Lib.Utils;
using Lib.Com;

namespace MS.INV.Systems
{
    public class WebComClient
    {
        BackgroundWorker worker = new BackgroundWorker();

        public Lib.Com.WebCom.QueryResult QueryResult
        {
            get 
            {
                Lib.Com.WebCom.QueryResult result = new Lib.Com.WebCom.QueryResult();
                result.url = Options.Url;
                result.serial = Options.CPU;
                result.keyCode = Options.KeyCode;
                result.ver = Options.CurrentVerion;
                result.passKey = Lib.Utils.Uti.KeyEncrypt;
                result.dbname = Lib.Data.ConnInfo.DatabaseName;
                result.usname = Lib.Data.ConnInfo.UserName;
                result.dbpass = Lib.Data.ConnInfo.Password;
                return result;
            }
        }

        public void Start()
        {
            if (!Systems.Options.AutoUpdateFromInternet) return;
                
            if (!Lib.Data.ConnInfo.IsServer) return;

            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerAsync();
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                Lib.Com.WebCom com = new Lib.Com.WebCom();
                com.QueryDone += new Lib.Com.WebCom.QueryDoneHandler(com_QueryDone);
                com.Query(this.QueryResult);
            }
            catch (Exception ex)
            {
                //Lib.Bases.SysError.RaiseError(ex, "WebCom class", "Communication to Web");
            }
        }

        void com_QueryDone(Lib.Com.WebCom.QueryResult result)
        {
            if (!Is.IsNullOrEmpty(result.keyCode) && result.keyCode.Length > 0)
            {
                using (ZZ_System sys = new ZZ_System())
                {
                    sys.ArgUpdate(6, "Agr2", result.keyCode);
                    Options.KeyCode = result.keyCode;
                }
            }
            if (!Is.IsNullOrEmpty(result.UrlDownload) && result.UrlDownload.Length > 0 && result.UrlDownload.ToString().ToLower() != "no")
            {
                Downloader down = new Downloader();
                down.Url = result.UrlDownload;
                down.ProgressChanged += new Downloader.DownloadHandler(down_ProgressChanged);
                down.DownloadFile();
            }
        }

        void down_ProgressChanged(Downloader.DownSender sender)
        {
            if (sender.DownloadCompleted)
            {
                Lib.Update.UpdateForm up = new Lib.Update.UpdateForm();
                up.AppCall = true;
                up.RunUpdate();
            }
        }
    }
}
